<template>
  <view>
    <view
        class="flex align-center justify-center relative h-130 sticky z-3 bg-fff"
        id="container"
        v-if="isManagerOrAdmin"
        :style="{top:`${top}px`}"
    >
      <!--骨架屏-->
      <view v-if="loading">
        <view class="flex align-center justify-center pb-30 pt-50">
          <view class="h-60 w-200 br-5 bg-f4f7f4"> </view>
          <view class="w-30 h-5 br-5 m-lr-10"></view>
          <view class="h-60 w-200 br-5 bg-f4f7f4"></view>
          <view class="h-60 w-180 br-5 bg-f4f7f4 ml-20"></view>
        </view>
      </view>

      <date-picker
        v-if="!loading"
        class="datePicker z-999"
        @changeTime="changeTime"
        :isSimplify="true"
      >
      </date-picker>
      <view class="relative w-full">
        <text class="absolute w-28 h-28 bg-FF6262 br-17 p-lr-10 color-fff fz-24 lh-34 right-202 z-999" style="top:-8rpx" v-if="groupSelect"></text>
        <u-dropdown
            v-if="!loading"
            ref="uDropdown"
            height="80"
            inactive-color="#2D8CF0"
            :close-on-click-mask="false"
            menu-icon="arrow-down-fill"
            close="dropDownClose"
        >
        <u-dropdown-item :title="title">
          <view class="bg-fff pb-30">
            <u-checkbox-group class="w-full" size="40">
              <view class="w-full flex flex-column p-lr-20">
                <view
                    v-for="(item, index) in checkedStatusList"
                    :key="index"
                    class="h-90 border-333333 br-10 pl-25 w-full flex align-center mb-18">
                  <u-checkbox
                      class="w-full flex"
                      :name="item.label"
                      v-model="item.checked"
                      :disabled="false"
                      shape="circle"
                      active-color="#19BE6B">
                    <text class="color-333333 fz-32 ml-30" > {{ item.label }} </text>
                  </u-checkbox>
                </view>
              </view>
            </u-checkbox-group>
            <view
                v-if="checkedNumber"
                class="m-lr-20 h-100 br-10 bg-2D8CF0 text-center fz-32 lh-100 color-fff"
                @tap="confirmStatus"
            >
              <text>确定</text>
            </view>
            <view
                v-else
                class="m-lr-20 h-100 br-10 bg-BEBEBE text-center fz-32 lh-100 color-fff"
            >
              <text>确定</text>
            </view>
          </view>
        </u-dropdown-item>
        <u-dropdown-item title="工单组别">
          <view class="bg-fff pb-30">
            <u-radio-group class="w-full" size="40" v-model="groupValue" @change="radioGroupChange">
              <view class="w-full flex flex-column p-lr-20">
                <view
                    v-for="(item, index) in options"
                    :key="index"
                    class="min-h-90 border-333333 br-10 pl-25 flex align-center mb-18">
                  <u-radio
                      style="width: 100% !important;"
                      :name="item.groupId"
                      :disabled="false"
                      shape="circle"
                      active-color="#19BE6B">
                    <view class="color-333333 fz-32 ml-30 break-all lh-40" > {{ item.groupName }} </view>
                  </u-radio>
                </view>
              </view>
            </u-radio-group>
            <view class="m-lr-20 h-100 br-10 bg-2D8CF0 text-center fz-32 lh-100 color-fff" @click="groupConfirm">
              <text>确定</text>
            </view>
          </view>
        </u-dropdown-item>
      </u-dropdown>
    </view>
    </view>
    <!--骨架屏-->
    <list-skeleton v-if="loading"></list-skeleton>
    <view :style="{minHeight:`calc(100vh - ${top}px - ${safeAreaInsets}px - 338rpx)`}">
      <view v-if="maintenanceList.length && !loading">
        <view
            class="flex"
            v-for="item in maintenanceList"
            :key="item.workOrderId"
            @longpress="handleLongpress"
        >
          <view
              class="w-50 flex align-center align-center ml-20"
              v-if="isLongpress"
              @tap.stop=""
          >
            <u-checkbox
                size="50"
                v-model="item.checked"
            ></u-checkbox>
          </view>
          <view class="m-lr-20 mb-30 pl-20 p-tb-12 flex1 flex align-center justify-between bg-E9F8FF br-10 oh" @tap="clickItem(item)">
            <view class="flex flex-column oh">
              <text class="fz-40 font-bold lh-56 mt-12 break-all text-ellipsis">{{ item.workOrderName || '-'}}</text>
              <text class="fz-28 lh-40 mt-20 text-ellipsis" v-if="item.status !== '0'">保养工程师: {{item.mroUser || '-'}}</text>
              <view class="flex mt-20">
                <text class="fz-28 lh-40">
                  起止时间：
                </text>
                <view class="flex flex-column fz-28 lh-40">
                  <text>{{ timeFormat(item.workOrderStartDate, item.workOrderStartTime)}}</text>
                  <text>{{ timeFormat(item.workOrderEndDate, item.workOrderEndTime)}}</text>
                </view>
              </view>
            </view>
            <view class="relative mr-30" >
              <CustomCircleProgress
                  :border-width="8"
                  :size="128"
                  :percent="percent(item)"
                  :active-color="activeColor(item)"
              >
                <view
                    class="h-full w-full lh-center"
                    :style="{color: item.status === '4' || item.status === '5' ? '#19BE6B' : item.status === '2' || item.status === '6' ? '#FF6262' : 'black'}"
                >
                  <text class="fz-30">{{showContent(item)}}</text>
                </view>
              </CustomCircleProgress>
            </view>
          </view>
        </view>

      </view>
      <empty-icon v-else></empty-icon>
    </view>


    <view
      class="flex align-center justify-between h-120 sticky bottom-100 bg-fff z-10 p-lr-50"
      v-if="isLongpress"
      :style="{bottom : `calc(100rpx + ${safeAreaInsets}px)`}"
    >
      <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center" @tap="cancleLongPress">
        <text>取消</text>
      </view>
      <view class="flex">
        <view
          class="h-60 w-200 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-20"
          :class="isAllowDelay ? 'allowDelay' : 'disAllowDelay'"
          @tap="isTimePickerShow = isAllowDelay"
        >
          <text>延长工单</text>
        </view>
        <view
          class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center"
          :class="isAllowDispatch ? 'allowDispatch' : 'disAllowDispatch'"
          @tap="dispatch"
        >
          <text>派单</text>
        </view>
      </view>
    </view>

    <u-picker
        :defaultTime="defaultTime"
        v-model="isTimePickerShow"
        :params="params"
        mode="time"
        safe-area-inset-bottom
        :title="title"
        @confirm="confirmDelay"
        control
    >
    </u-picker>
  </view>
</template>

<script>
import CustomCircleProgress from '../../components/CustomCircleProgress'
import getNavBarHeight from "@/mixins/getNavBarHeight";
import DatePicker from "@/components/DatePicker/DatePicker";
import EmptyIcon from "@/components/EmptyIcon/EmptyIcon";
import dayjs from '@/libs/dayjs.min.js'
import {list, delayEndDateBatch , groupOption } from "@/api/maintenance/task";
import ListSkeleton from "../../components/ListSkeleton";
import { MAINTENANCE_ORDER_STATUS } from '@/utils/dict'
export default {
  name: "maintenanceAll",
  components: {ListSkeleton, EmptyIcon, DatePicker, CustomCircleProgress},
  mixins:[getNavBarHeight],
  props:['isManagerOrAdmin'],
  data() {
    return {
      groupSelect:false,
      groupValue:'',
      options: [],
      hasNext: false,
      pageNum: 1,
      pageSize: 10,
      maintenanceList: [],
      startTime: '',
      endTime: '',
      title: '全部类型',
      checkedStatusList: [],
      checkedNumber: 2,
      loading: true,
      isLongpress: false,
      safeAreaInsets: 0, //底部安全区高度
      isAllowDispatch: false, //是否允许派单
      isAllowDelay: false, //是否允许延长截止时间
      defaultTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      isTimePickerShow: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
    }
  },
  created(){
    if(this.$store.getters.isFromHome2Work){
      const orderType = this.$store.getters.orderType
      if(orderType==='unDone'){
        const TO_MAINTENANCE = MAINTENANCE_ORDER_STATUS[1]
        const DO_MAINTENANCE = MAINTENANCE_ORDER_STATUS[3]
        this.checkedStatusList = MAINTENANCE_ORDER_STATUS.map(e=>{
          const el = { ...e, checked: false }
          const status = el.value
          if(status === TO_MAINTENANCE.value || status === DO_MAINTENANCE.value ){
            el.checked = true
          }
          return el
        })
        this.title = `${TO_MAINTENANCE.label},${DO_MAINTENANCE.label}`
      }else if(orderType==='done'){
        const DONE = MAINTENANCE_ORDER_STATUS[4]
        const SIGN = MAINTENANCE_ORDER_STATUS[5]
        this.checkedStatusList = MAINTENANCE_ORDER_STATUS.map(e=>{
          const el = { ...e, checked: false }
          const status = el.value
          if(status === DONE.value || status === SIGN.value ){
            el.checked = true
          }
          return el
        })
        this.title = `${DONE.label},${SIGN.label}`
      }
      this.$store.commit('SET_ISFROMHOME2WORK', false)
    }else{
      this.checkedStatusList = MAINTENANCE_ORDER_STATUS.map(el=>{ return {...el,checked:true} })
    }

    uni.getSystemInfo({
      success: (res) => {
        // #ifdef MP-WEIXIN
        this.safeAreaInsets = res.screenHeight - res.safeArea.bottom
        // #endif
        // #ifndef MP-WEIXIN
        this.safeAreaInsets = res.safeAreaInsets.bottom
        // #endif
      }
    })
    this.getGroupOptions()
    this.doQuery().then(res => {
      this.hasNext = res.hasNext
      this.maintenanceList = res.rows.map(item => {
        return {...item, checked: false}
      })
    }).finally(() => {
      this.loading = false
    })
  },
  watch:{
    checkedStatusList:{
      handler(newValue){
        let checkedArray = newValue.filter(item => {
          return item.checked
        })
        this.checkedNumber = checkedArray.length
      },
      deep: true,
      immediate: true
    },
    maintenanceList:{
      handler(newValue){
        const checkedArray = newValue.filter(item => item.checked)
        if(!checkedArray.length){
          this.isAllowDispatch = false
          this.isAllowDelay = false
          return
        }
        this.isAllowDispatch = checkedArray.every(item => {
          return item.status === '0' || item.status === '1' || item.status === '3'
        })
        this.isAllowDelay = checkedArray.every(item => {
          return item.status === '2' || item.status === '6'
        })
      },
      deep: true
    }
  },
  methods:{
    radioGroupChange(value){
      if(value){
        this.groupSelect = true
      }else{
        this.groupSelect = false
      }
    },
    getGroupOptions(){
      const companyId = this.$store.getters.companyId || ''
      const hospitalId = this.$store.getters.curHospitalId || ''
      groupOption({companyId,hospitalId}).then(res=>{
        this.options = res.data.map(el => ( { ...el,checked:false } )) || []
      })
    },
    groupConfirm(){
      this.pageNum = 1
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.maintenanceList= res.rows.map(item => {
          return {...item, checked: false}
        })
      })
      this.$refs.uDropdown.close();
    },
    dropDownClose(){
    },
    //批量延长截止时间
    confirmDelay(e){
      const now = new Date()
      let delayEndDate = `${e.year}-${e.month}-`
      if(now.getFullYear() === parseInt(e.year) && now.getMonth()+1 === parseInt(e.month) && now.getDate() > parseInt(e.day)){
        delayEndDate += now.getDate()
      }else{
        delayEndDate += e.day
      }
      const workOrderIdList = this.maintenanceList.filter(item => item.checked).map(item => item.workOrderId)
      delayEndDateBatch({workOrderIdList, delayEndDate}).then(res => {
        if(res.code == 200){
          this.pageNum = 1
          this.isLongpress = false
          this.doQuery().then(res => {
            this.hasNext = res.hasNext
            this.maintenanceList= res.rows.map(item => {
              return {...item, checked: false}
            })
          })
        }
      })
    },
    //派单操作(批量分配工程师)
    dispatch(){
      if(this.isAllowDispatch){
        const workOrderIdList = this.maintenanceList.filter(item => item.checked).map(item => item.workOrderId)
        const hospitalId = this.maintenanceList.filter(item => item.checked)[0].hospitalId
        this.$tab.navigateTo('/pages/maintenance/choose-worker?workOrderIdList=' + workOrderIdList + '&hospitalId=' + hospitalId + '&byBatch=1')
      }
    },
    //取消长按多选
    cancleLongPress(){
      this.maintenanceList.forEach(item => {
        item.checked = false
      })
      this.isLongpress = false
    },
    handleLongpress(){
      //长按手机震动并且显示复选框
      uni.vibrateShort({
        success: function() {}
      });
      this.isLongpress = true
    },
    activeColor(item){
      //待分配 超时未开始
      if(item.status === '0' || item.status === '2'){
        return '#DFDFDF'
      }
      //未开始 进行中 保养超时
      if(item.status === '1' || item.status === '3' || item.status === '6'){
        return Math.floor((item.finishProject / item.totalProject)*100) > 75 ? Math.floor((item.finishProject / item.totalProject)*100) >= 100 ? '#19BE6B' : '#FF9900' : '#FF6262'
      }
      //保养结束 已签名
      if(item.status === '4' || item.status === '5'){
        return '#19BE6B'
      }
    },
    percent(item){
      //待分配 超时未开始
      if(item.status === '0' || item.status === '2'){
        return 0
      }
      //未开始 进行中 保养超时
      if(item.status === '1' || item.status === '3' || item.status === '6'){
        return Math.floor((item.finishProject / item.totalProject)*100) > 100 ? 100 : Math.floor((item.finishProject / item.totalProject)*100)
      }
      //保养结束 已签名
      if(item.status === '4' || item.status === '5'){
        return 100
      }
    },
    showContent(item){
      //待分配
      if(item.status === '0'){
        return '待分配'
      }
      //超时未开始 保养超时
      if(item.status === '2' || item.status === '6'){
        return '超时'
      }
      //保养结束
      if(item.status === '4'){
        return '已完成'
      }
      //已签名
      if(item.status === '5'){
        return '已签名'
      }
      //待开始
      if(item.status === '1'){
        return '待开始'
      }
      if(!item.totalProject){
        return '-'
      }
      // 进行中
      if(item.status === '3'){
        return Math.floor((item.finishProject / item.totalProject)*100) > 100 ? '100%' : Math.floor((item.finishProject / item.totalProject)*100) + '%'
      }
    },
    //确定选择工单状态
    confirmStatus() {
      if(this.checkedNumber === 1){
        this.title = this.checkedStatusList.find(item => {
          return item.checked
        }).label
      }
      else if(this.checkedNumber === this.checkedStatusList.length){
        this.title = '全部类型'
      }
      else{
        this.title = this.checkedStatusList.find(item => {
          return item.checked
        }).label + '...'
      }
      this.pageNum = 1
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.maintenanceList= res.rows.map(item => {
          return {...item, checked: false}
        })
      })
      this.$refs.uDropdown.close();
    },
    clickItem(item) {
      if(!this.isLongpress){
        this.$tab.navigateTo('/pages/maintenance/maintenance-order-detail?workOrderId='+item.workOrderId)
      }
      else{
        item.checked = !item.checked
      }
    },
    reachBottom(){
      if(this.hasNext){
        this.pageNum ++
        this.doQuery().then(res => {
          this.hasNext = res.hasNext
          this.maintenanceList= [...this.maintenanceList,...res.rows.map(item => {
            return {...item, checked: false}
          })]
        })
      }
    },
    changeTime(e){
      this.pageNum = 1
      this.startTime = e.startTime ? dayjs(e.startTime).format('YYYY-MM-DD') : '';
      this.endTime = e.endTime ? dayjs(e.endTime).format('YYYY-MM-DD') : '';
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.maintenanceList= res.rows.map(item => {
          return {...item, checked: false}
        })
      })
    },
    doQuery(){
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        maintenanceStartDate: this.startTime,
        maintenanceEndDate: this.endTime,
        groupId : this.groupValue
      }
      if(this.checkedNumber === 1){
        let checked = this.checkedStatusList.find(item => {
          return item.checked
        })
        if(checked.label === '待完成' || checked.label === '已完成'){
          params.statusList = checked.value
        }else{
          params.status = checked.value
        }

      }else{
        let statusList = this.checkedStatusList.reduce((pre, next) => {
          if(next.checked){
            pre.push(next.value)
          }
          return pre
        },[]).join()
        params.statusList = statusList
      }
      return list(params).then(res => {
        return Promise.resolve(res)
      }).catch(() => {
        this.loading = false
      })
    },
    timeFormat(date, time){
      if(!date || !time){
        return '-'
      }
      return date + ' ' + time.split(':')[0] + ":" + time.split(':')[1]
    },
  }
}
</script>

<style lang="scss" scoped>
.datePicker{
  position: absolute;
  left: 20rpx;
  top: 26rpx;
}
.allowDispatch{
  border: 2rpx solid #2d8cf0;
  background: #2d8cf0;
}
.disAllowDispatch{
  border: 2rpx solid #2d8cf050;
  background: #2d8cf050;
}
.disAllowDelay{
  border: 2rpx solid #CCCCCC;
  color: #88888850;
  background: #F1F1F150;
}
.allowDelay{
  border: 2rpx solid #2d8cf0;
  color: #2d8cf0;
}
/deep/.u-dropdown__menu{
  display: block !important;
  overflow: hidden !important;
  padding-right: 10rpx !important;
  background-color: #FFFFFF;
  text-align: right;
  overflow: visible !important;
}
/deep/.u-dropdown__menu__item{
  float: right !important;
  margin-right: 10rpx;
}
/deep/ .u-dropdown__content__popup{
  max-height: 880rpx;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
